////////////////////////////////////////////////////////
//
//  Copyright(C), 2005-2022, GEC Tech. Co., Ltd.
//  www.yueqian.com.cn  ALL RIGHT RESERVED
//
//  文件: broadcast-send.c
//  描述: 发送UDP广播数据
//
///////////////////////////////////////////////////////

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <fcntl.h>

int main(int argc, char const *argv[]) // ./send 对方的IP
{
    if(argc != 2)
    {
        printf("请指定UDP广播地址\n");
        exit(0);
    }

    // 绑定地址
    // 创建UDP套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    // 使能套接字的广播属性
    int on = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));

    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_port = htons(50021);

    // 将数据发送到广播地址
    char *msg = "abcdefg...";
    int n = sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr*)&addr, sizeof(addr));
    if(n < 0)
        perror("发送失败");
    else
        printf("已发送%d个字节\n", n);

    close(sockfd);
    return 0;
}